package com.sai.jsai.common.starter.web.handler;

import com.sai.jsai.common.base.exception.CommonBizErrorCode;
import com.sai.jsai.common.base.exception.CommonBizException;
import com.sai.jsai.common.base.exception.SystemException;
import com.sai.jsai.common.base.vo.RestResult;
import org.springframework.http.HttpStatus;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.ArrayList;
import java.util.List;

/**
 * @author jisai
 * @version 0.0.1
 * @Description TODO
 * @createTime 2024/09/21
 */
@ControllerAdvice
public class GlobalWebExceptionHandler {
    /**
     * 自定义方法参数校验异常处理器
     *
     * @param ex
     * @return
     */
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public RestResult<String> handleValidationExceptions(MethodArgumentNotValidException ex) {
        List<String> errorsMsg = new ArrayList<>();
        ex.getBindingResult().getAllErrors().forEach((error) -> {
            String fieldName = ((FieldError) error).getField();
            String errorMessage = error.getDefaultMessage();
            errorsMsg.add(String.format("[%s]%s", fieldName, errorMessage));
        });
        return RestResult.error(CommonBizErrorCode.VALIDATION_FAIL.getCode(), "请求参数错误: " + String.join("; ", errorsMsg));
    }

    /**
     * 自定义业务异常处理器
     *
     * @param bizException
     * @return
     */
    @ExceptionHandler(CommonBizException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public RestResult<String> commonBizExceptionHandler(CommonBizException bizException) {
        return RestResult.error(bizException.getErrorCode().getCode(), bizException.getErrorCode().getMessage());
    }

    /**
     * 自定义系统异常处理器
     *
     * @param systemException
     * @return
     */
    @ExceptionHandler(SystemException.class)
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public RestResult<String> systemExceptionHandler(SystemException systemException) {
        return RestResult.error(systemException.getErrorCode().getCode(), systemException.getErrorCode().getMessage());
    }

}
